package leetcode;

import java.util.Arrays;

public class LeetCode31 {

    public static void main(String[] args) {
        LeetCode31 leetCode31 = new LeetCode31();
        leetCode31.nextPermutation(new int[]{1, 1});
    }

    //暴力法不能执行通过
    public void nextPermutation1(int[] nums) {
        int lastNum = nums[nums.length - 1];
        for (int i = nums.length - 2; i >= 0; i--) {
            if (nums[i] < lastNum) {
                nums[nums.length - 1] = nums[i];
                nums[i] = lastNum;
                return;
            }
        }
        int tmp, i = 0, j = nums.length - 1;
        while (i < j) {
            tmp = nums[i];
            nums[i] = nums[j--];
            nums[i++] = tmp;
        }
    }

    public void nextPermutation(int[] nums) {
        int i = nums.length - 2;
        while (i >= 0 && nums[i + 1] <= nums[i]) {
            i--;
        }
        if (i >= 0) {
            int j = nums.length - 1;
            while (j >= 0 && nums[j] <= nums[i]) {
                j--;
            }
            swap(nums, i, j);
        }
        reverse(nums, i + 1);
    }

    private void reverse(int[] nums, int start) {
        int i = start, j = nums.length - 1;
        while (i < j) {
            swap(nums, i, j);
            i++;
            j--;
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
//------------------------------------------------------------------
}
